# Create your views here.
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from django.template import loader
from .models import Question


def index(request):
    print('进入index\n请求地址是：')
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request))


def index1(request):
    """
【载入模板，填充上下文，再返回由它生成的 HttpResponse 对象】
    :param request:
    :return:
    """
    print('进入index1\n请求地址是：')
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request))


def index2(request):
    """
改进index1，使用render
    :param request:
    :return:
    """
    print('进入index2\n请求地址是：')
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)


def son1(request):
    print('进入son1\n请求地址是：')
    return HttpResponse('hello son1')


def son2(request):
    print('进入son2\n请求地址是：')
    return HttpResponse('hello son2')


def sun1(request):
    print('进入sun1\n请求地址是：')
    return HttpResponse('hello sun1')


def sun2(request):
    print('进入sun2\n请求地址是：')
    return HttpResponse('hello sun2')


def detail(request, question_id):
    print('进入detail，question_id=', question_id)
    # try:
    #     question = Question.objects.get(id=question_id)     # 这里pk=question_id和id=question_id等价
    # except Question.DoesNotExist:
    #     raise Http404("Question does not exist")

    # 或者将上面try语句过程简单写成以下语句
    question = get_object_or_404(Question, pk=question_id)      # 还有get_list_or_404() 函数
    return render(request, 'polls/detail.html', {'question': question})


def results(request, question_id):
    print('results，question_id=', question_id)
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)


def vote(request, question_id):
    print('vote，question_id=', question_id)
    return HttpResponse("You're voting on question %s." % question_id)
